import process from 'node:process'

import { defineConfig, presetIcons, presetUno, transformerDirectives, transformerVariantGroup } from 'unocss'
import { presetApplet, presetRemRpx } from 'unocss-applet'

const regPX = /(-?[.\d]+)px/g
const directionMap: Record<string, string> = { t: 'top', r: 'right', b: 'bottom', l: 'left' }

export default defineConfig({
  presets: [
    presetUno(),
    presetIcons(),
    presetApplet(),
    // presetRemRpx({
    //   baseFontSize: 16,
    //   screenWidth: 750,
    //   mode: 'rpx2rem',
    // }),
  ],
  transformers: [
    transformerDirectives(),
    transformerVariantGroup(),
  ],
  postprocess: (util) => {
    util.entries.forEach((i) => {
      const value = i[1]
      if (value && typeof value === 'string' && regPX.test(value)) {
        i[1] = value.replace(regPX, (_, a) => `${a}rpx`)
      }
    })
  },
  theme: {
    preflightRoot: ['page,::before,::after'],
    colors: {
      theme: {
        primary: {
          yellow: '#f7920d',
          blue: '#1677FF',
        }[process.env.PRODUCT_THEME!],

        red: '#E52E2E',
        pagebg: '#f4f5f9',
      },
    },
    fontFamily: {
      system: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif',
    },
  },
  rules: [],
  shortcuts: [
    // 颜色
    [/^(text|bg|b(-([trlbxy]))?|shadow|from|to)-#([0-9A-Fa-f]{1,6})(\/.+)?$/, ([, a, , , b, c]) => {
      if (b.length > 2) {
        return `${a}-#${b}${c ?? ''}`
      }
      return `${a}-#${''.padEnd(6, b)}${c ?? ''}`
    }],
    // 安全区域 margin、padding
    [/^safe-([mp])([trbl])(-(.+))?$/, ([, a, b, , c]) => {
      return `${a}${b}-[max(env(safe-area-inset-${directionMap[b]}),${c ?? '0px'})]`
    }],
    // 安全区域 width、height
    [/^safe-([wh])-([trbl])(-(.+))?$/, ([, a, b, , c]) => {
      return `${a}-[max(env(safe-area-inset-${directionMap[b]}),${c ?? '0px'})]`
    }],
    {
      'btn-primary-black': {
        yellow: 'rd-full bg-black text-center text-theme-primary active:op-85',
        blue: 'rd-full bg-theme-primary text-center text-white active:op-85',
      }[process.env.PRODUCT_THEME!]!,

      'btn-primary-theme': {
        yellow: 'rd-full bg-theme-primary text-center text-white active:op-85',
        blue: 'rd-full bg-theme-primary text-center text-white active:op-85',
      }[process.env.PRODUCT_THEME!]!,

      // 'btn-secondary-theme': 'rd-full bg-#fff6eb text-center text-theme-primary b-2px b-solid b-theme-primary active:op-85',
      'btn-secondary-theme': 'rd-full bg-theme-primary/10 text-center text-theme-primary b-2px b-solid b-theme-primary active:op-85',

      'routine-lh': 'lh-[1.2]',
      'form-item-important-mark': 'before-content-[\'*\'] before-text-theme-red',
    },
  ],
  safelist: [],
})
